import 'package:compass/components/row.dart';
import 'package:flutter/cupertino.dart';
import '../const/permission_list.dart';
import '../utils/permission.dart';

class PermissionSwitch extends StatefulWidget {
  const PermissionSwitch({super.key, this.onChanged});

  final Function(bool value)? onChanged;

  @override
  State<PermissionSwitch> createState() => _PermissionSwitchState();
}

class _PermissionSwitchState extends State<PermissionSwitch> {
  bool _switchValue = false;

  @override
  void initState() {
    super.initState();
    _checkPermission().then((value) {
      _informChanged(value);
    });
  }

  Future<bool> _checkPermission() async {
    final res = await checkPermission(permissionList);
    setState(() {
      _switchValue = res;
    });
    return res;
  }

  void _informChanged(bool value) {
    if (widget.onChanged != null) {
      widget.onChanged!(value);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
      child: RowControl(
        label: '打开位置及传感器权限',
        content: CupertinoSwitch(
          // This bool value toggles the switch.
          value: _switchValue,
          activeColor: CupertinoColors.activeBlue,
          onChanged: (bool? value) {
            // This is called when the user toggles the switch.
            final newValue = value ?? false;
            if (newValue) {
              _checkPermission().then((value) {
                _informChanged(value);
              });
            } else {
              _informChanged(newValue);
            }
          },
        ),
      ),
    );
  }
}
